package com.weetop.aklyscan.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.LogUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.weetop.aklyscan.R;
import com.weetop.aklyscan.activity.lanya.BluetoothLeClass;
import com.weetop.aklyscan.activity.lanya.Bluetooth_Scale;
import com.weetop.aklyscan.activity.lanya.DeviceListActivity;
import com.weetop.aklyscan.activity.lanya.PubFunction;
import com.weetop.aklyscan.activity.qingdan.DetailedActivity;
import com.weetop.aklyscan.activity.sreach.SearchPositionActivity1;
import com.weetop.aklyscan.activity.sreach.SearchPositionActivity2;
import com.weetop.aklyscan.activity.sreach.SearchPositionActivity3;
import com.weetop.aklyscan.activity.sreach.SearchPositionActivity4;
import com.weetop.aklyscan.activity.sreach.SearchPositionActivity5;
import com.weetop.aklyscan.activity.sreach.SearchPositionActivity6;
import com.weetop.aklyscan.activity.sreach.SearchPositionActivity7;
import com.weetop.aklyscan.activity.sreach.SearchPositionActivity8;
import com.weetop.aklyscan.appConfig.MyApplication;
import com.weetop.aklyscan.base.BaseActivity;
import com.weetop.aklyscan.base.mvp.BaseModel;
import com.weetop.aklyscan.bean.UserInfoBean;
import com.weetop.aklyscan.bean.VersionBean;
import com.weetop.aklyscan.presenter.LoginPresent;
import com.weetop.aklyscan.utils.BaseUtils;
import com.weetop.aklyscan.view.LoginView;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import ZPL.ZPLPrinterHelper;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cc.shinichi.library.tool.utility.ui.ToastUtil;
import update.UpdateAppUtils;

public class MainActivity extends BaseActivity<LoginPresent> implements LoginView {
    @BindView(R.id.Le_01)
    LinearLayout Le_01;
    @BindView(R.id.Le_02)
    LinearLayout Le_02;
    @BindView(R.id.Le_03)
    LinearLayout Le_03;
    @BindView(R.id.Le_04)
    LinearLayout Le_04;
    @BindView(R.id.Le_05)
    LinearLayout Le_05;
    @BindView(R.id.Le_06)
    LinearLayout Le_06;
    @BindView(R.id.Le_07)
    LinearLayout Le_07;
    @BindView(R.id.Le_08)
    LinearLayout Le_08;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.versionName)
    TextView versionName;
    @BindView(R.id.updata)
    TextView updata;
    @BindView(R.id.dylj)
    TextView dylj;
    @BindView(R.id.dy_status)
    ImageView dy_status;
    @BindView(R.id.shebei)
    TextView shebei;
    @BindView(R.id.status)
    TextView status;
    @BindView(R.id.ll2)
    LinearLayout ll2;
    @BindView(R.id.dayin_ll)
    LinearLayout dayin_ll;
    @BindView(R.id.bluetooth_shebei)
    TextView bluetooth_shebei;
    @BindView(R.id.iv_bluetooth_status)
    ImageView iv_bluetooth_status;
    @BindView(R.id.tv_bluetooth_status)
    TextView tv_bluetooth_status;
    @BindView(R.id.bluetooth_ll)
    LinearLayout bluetooth_ll;

    String upUrl;
    int versionCode;
    public static ZPLPrinterHelper mZPL;
    public static UserInfoBean userInfoBean;
    private boolean dyjStatus;

    private AssetManager assetManager;
    private MediaPlayer player = new MediaPlayer();
    private boolean isPlay;

    private void playRing(String fileName) {
        try {
            isPlay = false;
            assetManager = getAssets();
            AssetFileDescriptor fileDescriptor = assetManager.openFd(fileName);
//            if (player.isPlaying()) {
            player.reset();
//            }
            player.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(),
                    fileDescriptor.getLength());
            player.prepare();
            player.start();
            player.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                @Override
                public void onSeekComplete(MediaPlayer mp) {
                    player.stop();
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                if (ZPLPrinterHelper.IsOpened()) {
                    status.setText("连接成功");
                    dy_status.setImageResource(R.mipmap.select_true);
                } else {
                    status.setText("连接失败");
                    dy_status.setImageResource(R.mipmap.error);
                }
            } else if (msg.what == 2) {
                getDayinStatus();
                handler.sendEmptyMessageDelayed(2, 3000);
            } else if (msg.what == 4) {
                if (MyApplication.b_scaleIsConnect == Boolean.TRUE) {
                    tv_bluetooth_status.setText("连接成功");
                    iv_bluetooth_status.setImageResource(R.mipmap.select_true);
                } else {
                    tv_bluetooth_status.setText("连接失败");
                    iv_bluetooth_status.setImageResource(R.mipmap.error);
                }
            } else if (msg.what == 3) {
                if (MyApplication.b_scaleIsConnect == Boolean.TRUE) {
                    tv_bluetooth_status.setText("连接成功");
                    iv_bluetooth_status.setImageResource(R.mipmap.select_true);
                    if (MyApplication.isBluePlay == 0 || MyApplication.isBluePlay == 2) {
                        MyApplication.isBluePlay = 1;
                        playRing("lianjiesuccess.mp3");
                    }
                } else {
                    tv_bluetooth_status.setText("连接失败");
                    iv_bluetooth_status.setImageResource(R.mipmap.error);
                    if (MyApplication.isBluePlay == 1) {
                        MyApplication.isBluePlay = 2;
                        playRing("lianjieerror.mp3");
                    }
                }
            }
        }
    };

    @Override
    protected LoginPresent createPresenter() {
        return new LoginPresent(this, this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mZPL = ZPLPrinterHelper.getZPL(mContext);
        versionName.setText("当前版本：V " + getPackageInfo(MainActivity.this).versionName);
        tvName.setText(MyApplication.getUserName());
        mPresenter.getVersion();
        if (MyApplication.getPort().equals("1")) {
            Le_03.setVisibility(View.VISIBLE);
            Le_04.setVisibility(View.GONE);
            Le_06.setVisibility(View.VISIBLE);
            Le_07.setVisibility(View.VISIBLE);
            Le_08.setVisibility(View.VISIBLE);
            ll2.setVisibility(View.VISIBLE);
            bluetooth_ll.setVisibility(View.VISIBLE);

            bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (bluetoothAdapter != null) {
                if (bluetoothAdapter.isEnabled()) {
                    Set<BluetoothDevice> bluetoothDevices = bluetoothAdapter.getBondedDevices();
                    for (BluetoothDevice device : bluetoothDevices) {
                        //log打印蓝牙设备的名称和地址
                        Log.e("TAG", "decive name: " + device.getName());
                        Log.e("TAG", "device addr: " + device.getAddress());
                        if (device.getName().equals("KunhongScale30A")) {
//                        new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                try{
//                                    final BluetoothSocket socket = (BluetoothSocket) device.getClass().
//                                            getDeclaredMethod("createRfcommSocket", new Class[]{int.class}).invoke(device, 1);
//                                    bluetoothAdapter.cancelDiscovery();
//                                    socket.connect();
//                                }catch (Exception e){
//                                    e.printStackTrace();
//                                }
//                            }
//                        }).start();
//                        bluetoothAdapter.getRemoteDevice(device.getAddress());
                            mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
                        }
                    }
                } else {
                    ToastUtil.getInstance()._short(this, "未开启蓝牙");
                }
            } else {
                ToastUtil.getInstance()._short(this, "设备不支持蓝牙");
            }
            getBle();
            dayin_ll.setVisibility(View.VISIBLE);
        } else {
            dayin_ll.setVisibility(View.GONE);
            Le_03.setVisibility(View.GONE);
            Le_04.setVisibility(View.VISIBLE);
            Le_06.setVisibility(View.GONE);
            Le_07.setVisibility(View.GONE);
            Le_08.setVisibility(View.GONE);
            ll2.setVisibility(View.GONE);
            bluetooth_ll.setVisibility(View.GONE);
        }
    }

    @OnClick({R.id.Le_01, R.id.Le_02, R.id.Le_03, R.id.Le_04, R.id.Le_05, R.id.Le_06, R.id.Le_07, R.id.Le_08, R.id.updata, R.id.dylj, R.id.shebei, R.id.bluetooth_lj, R.id.bluetooth_shebei})
    public void onViewClicked(View view) {
        if (BaseUtils.fastClick())
            switch (view.getId()) {
                case R.id.bluetooth_lj:
                case R.id.bluetooth_shebei:
                    if (!mBluetoothAdapter.isEnabled()) {
                        Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        startActivityForResult(mIntent, 0);
                    } else {
                        Intent serverIntent = new Intent(this, DeviceListActivity.class);
                        startActivityForResult(serverIntent, 1);
                    }
                    break;
                case R.id.Le_01:
                    BaseUtils.toActivity(mActivity, NewScanInStockActivity.class);
                    break;
                case R.id.Le_02:
                    BaseUtils.toActivity(mActivity, NewScanOutActivity.class);
                    break;
                case R.id.Le_03:
                    BaseUtils.toActivity(mActivity, SendOutActivity.class);
                    break;
                case R.id.Le_04:
                    BaseUtils.toActivity(mActivity, PeijianInventoryActivity.class);
                    break;
                case R.id.Le_05:
                    if (MyApplication.getPort().equals("1")) {
                        XPopup.get(MainActivity.this).asCenterList("请选择类型", new String[]{"产品", "配件"},
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        if (position == 0) {
                                            XPopup.get(MainActivity.this).asCenterList("请选择类型", new String[]{"采购", "仓库", "销售"},
                                                    new OnSelectListener() {
                                                        @Override
                                                        public void onSelect(int position, String text) {
                                                            if (position == 0) {
                                                                BaseUtils.toActivity(mActivity, SearchPositionActivity1.class);
                                                            } else if (position == 1) {
                                                                BaseUtils.toActivity(mActivity, SearchPositionActivity2.class);
                                                            } else {
                                                                BaseUtils.toActivity(mActivity, SearchPositionActivity3.class);
                                                            }
                                                        }
                                                    })
                                                    .show();
                                        } else {
                                            XPopup.get(MainActivity.this).asCenterList("请选择类型", new String[]{"采购", "仓库", "销售"},
                                                    new OnSelectListener() {
                                                        @Override
                                                        public void onSelect(int position, String text) {
                                                            if (position == 0) {
                                                                BaseUtils.toActivity(mActivity, SearchPositionActivity4.class);
                                                            } else if (position == 1) {
                                                                BaseUtils.toActivity(mActivity, SearchPositionActivity5.class);
                                                            } else {
                                                                BaseUtils.toActivity(mActivity, SearchPositionActivity6.class);
                                                            }
                                                        }
                                                    })
                                                    .show();
                                        }
                                    }
                                })
                                .show();
                    } else {
                        XPopup.get(MainActivity.this).asCenterList("请选择类型", new String[]{"产品", "配件"},
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        if (position == 0) {
                                            BaseUtils.toActivity(mActivity, SearchPositionActivity7.class);
                                        } else {
                                            BaseUtils.toActivity(mActivity, SearchPositionActivity8.class);
                                        }
                                    }
                                })
                                .show();
                    }
                    break;
                case R.id.Le_06:
//                    BaseUtils.toActivity(mActivity, SCScanInStockActivity.class);
                    BaseUtils.toActivity(mActivity, InventoryActivity.class);
                    break;
                case R.id.Le_07:
                    BaseUtils.toActivity(mActivity, DetailedActivity.class);
                    break;
                case R.id.Le_08:
                    BaseUtils.toActivity(mActivity, ReturnGoodsActivity.class);
                    break;
                case R.id.updata:
                    if (TextUtils.isEmpty(upUrl)) {
                        ToastUtil.getInstance()._short(MainActivity.this, "未获取到更新信息");
                        return;
                    }
                    if (versionCode <= getPackageInfo(MainActivity.this).versionCode) {
                        UpdateAppUtils.getInstance().deleteInstalledApk();
                        ToastUtil.getInstance()._short(MainActivity.this, "已是最新版本");
                        return;
                    }
                    checkUpdate(upUrl);
                    break;
                case R.id.dylj:
                    if (!ZPLPrinterHelper.IsOpened() || !dyjStatus) {
                        LianjieDialog lianjieDialog = new LianjieDialog(this, dy_status, status, mPresenter);
                        lianjieDialog.show();
                    } else {
                        startActivity(new Intent(MainActivity.this, PrinterActivity.class));
                    }
                    break;
                case R.id.shebei:
                    if (!ZPLPrinterHelper.IsOpened() || !dyjStatus) {
                        LianjieDialog lianjieDialog = new LianjieDialog(this, dy_status, status, mPresenter);
                        lianjieDialog.show();
                    } else {
                        startActivity(new Intent(MainActivity.this, PrinterActivity.class));
                    }
                    break;
            }
    }

    @OnClick(R.id.tv_logout)
    public void onViewClicked() {
        if (BaseUtils.fastClick()) {
            XPopup.get(this).asConfirm("提示", "确认退出当前账户吗？",
                    new OnConfirmListener() {
                        @Override
                        public void onConfirm() {
                            MyApplication.setUserToken("");
                            BaseUtils.toActivity(MainActivity.this, LoginActivity.class);
                            finish();
                        }
                    })
                    .show();
        }
    }

    @Override
    public void getInto23Success(BaseModel<VersionBean> o) {
        VersionBean versionBean = o.getData();
        upUrl = versionBean.getPath();
        versionCode = versionBean.getVersion_number();
        if (TextUtils.isEmpty(upUrl)) {
            return;
        }
        if (versionCode <= getPackageInfo(MainActivity.this).versionCode) {
            UpdateAppUtils.getInstance().deleteInstalledApk();
            updata.setText("最新版本");
            updata.setBackgroundResource(R.drawable.et_bg);
            return;
        }
        updata.setText("等待更新");
        updata.setBackgroundResource(R.drawable.et_yellow);
    }

    @Override
    public void getInto44Success(BaseModel<String> o) {

    }

    boolean firstDy = true;

    @Override
    public void getInto45Success(BaseModel<UserInfoBean> o) {
        userInfoBean = o.getData();
        shebei.setText("打印设备：" + userInfoBean.getPrint_equipment());
        handler.post(runnable1);
    }

    private static boolean mBackKeyPressed = false;//记录是否有首次按键

    private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            Log.i("TAG", "000000:");
            if (status == BluetoothGatt.GATT_SUCCESS) {
                // 收到的数据
                byte[] receiveByte = characteristic.getValue();
                Log.i("TAG", "1111:" + receiveByte.toString());
            } else {
                Log.d("TAG", "接收数据失败-->" + status);
            }
        }

        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                Log.i("TAG", "连接成功");
                mBluetoothGatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                Log.d("TAG", "连接失败-->" + status);
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {//发现服务，在蓝牙连接的时候会调用
            Log.e("onCharacteristicRead中", "333333333333333");
        }

        @Override
        public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {//descriptor读
            Log.e("onCharacteristicWrite中", "数据接收了哦22222222222222222");
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {// Characteristic 改变，数据接收会调用
            Log.e("onCharacteristicWrite中", "数据接收了哦11111111111");
        }
    };

    private BluetoothAdapter bluetoothAdapter;

    private BluetoothDevice btDevice = null;
    private BluetoothGatt mBluetoothGatt = null;

    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
    private BluetoothAdapter mBluetoothAdapter = null;
    public Bluetooth_Scale btScale = null;
    public BluetoothLeClass bleScale = null;
    int BluetoothType;
    Fragment_send_out.SCALENOW scalenow = new Fragment_send_out.SCALENOW();
    String BluetoothAddress;
    final Boolean SendMoudle = true;  //  这个表示是连接称重模块

    public void getBle() {
        try {
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            ToastUtil.getInstance()._short(this, "不支持蓝牙");
            return;
        }

        mBluetoothAdapter.enable();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("此应用需要位置访问权限");
                builder.setMessage("请授予位置访问权限，以便此应用可以检测蓝牙。");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
                        }
                    }
                });
                builder.show();
            }
        }
        if (btScale == null) btScale = Bluetooth_Scale.getBluetooth_scale();
        btScale.setOnReceivedDataListener(onReceivedDataListener);
        btScale.setOnConnectBlueListener(onConnectBlueListener);
        if (bleScale == null) {
            bleScale = BluetoothLeClass.getBluetoothLeClass();
            bleScale.initialize();

            bleScale.setOnConnectListener(onConnectListener);
            bleScale.setOnDataAvailableListener(new BluetoothLeClass.OnDataAvailableListener() {
                @Override
                public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {

                }

                @Override
                public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
//                    byte[] buffer = characteristic.getValue();
//                    OnReceivedData(buffer);
                }
            });
        }
        ReadConfig();
    }

    public BluetoothLeClass.OnConnectListener onConnectListener = new BluetoothLeClass.OnConnectListener() {
        @Override
        public void onConnect(BluetoothGatt gatt, int type) {
            if (type == 0) {
                MyApplication.b_scaleIsConnect = true;

            } else if (type == 1) {
                MyApplication.b_scaleIsConnect = false;
            }
            handler.sendEmptyMessage(3);
        }
    };
    public Bluetooth_Scale.onReceivedDataListener onReceivedDataListener = new Bluetooth_Scale.onReceivedDataListener() {

        @Override
        public void onReceivedData(byte[] buf) {
        }
    };
    public Bluetooth_Scale.onConnectBlueListener onConnectBlueListener = new Bluetooth_Scale.onConnectBlueListener() {
        @Override
        public void onConnect(int what, int arg) {
            if (arg < 2) {
                MyApplication.b_scaleIsConnect = Boolean.FALSE;
            } else {
                MyApplication.b_scaleIsConnect = Boolean.TRUE;
            }
            handler.sendEmptyMessage(3);
        }
    };

    void ChkAndConnectBl() {
        if (MyApplication.b_scaleIsConnect)
            return;
        if (BluetoothAddress.length() > 0) {
            //ble或者双模模块
            if ((BluetoothType == BluetoothDevice.DEVICE_TYPE_LE)) {
                bleScale.connect(BluetoothAddress);
            } else {
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(BluetoothAddress);
                if (device != null) {
                    btScale.connect(device);
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0:
                if (resultCode == RESULT_OK) {
                    Intent serverIntent = new Intent(this, DeviceListActivity.class);
                    startActivityForResult(serverIntent, 1);
                }
                break;
            case 1:
                if (resultCode == RESULT_OK) {
                    //String name=data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
                    BluetoothAddress = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                    BluetoothType = data.getExtras().getInt(DeviceListActivity.EXTRA_DEVICE_TYPE);
                    if (BluetoothAddress.length() > 0) {
                        //ble或者双模模块
                        if ((BluetoothType == BluetoothDevice.DEVICE_TYPE_LE)) {
                            if ((bleScale != null) && bleScale.isConnect) {
                                bleScale.disconnect();
                            }
                            bleScale.connect(BluetoothAddress);
                            WriteConfig();
                        } else {
                            BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(BluetoothAddress);
                            if (device != null) {
                                btScale.connect(device);
                                WriteConfig();
                            }
                        }
                    }
                }
                break;
        }
    }

    public void ReadConfig() {
        SharedPreferences settings = getSharedPreferences(PubFunction.PREFS_NAME, Context.MODE_PRIVATE);
        BluetoothAddress = settings.getString("BluetoothAddress", "");
        BluetoothType = settings.getInt("BluetoothType", 0);
        bluetooth_shebei.setText("蓝牙设备：" + BluetoothAddress);
    }

    public void WriteConfig() {
        SharedPreferences settings = getSharedPreferences(PubFunction.PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt("BluetoothType", BluetoothType);
        editor.putString("BluetoothAddress", BluetoothAddress);
        editor.commit();
    }

    @Override
    public void onBackPressed() {
        if (!mBackKeyPressed) {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mBackKeyPressed = true;
            new Timer().schedule(new TimerTask() {//延时两秒，如果超出则擦错第一次按键记录
                @Override
                public void run() {
                    mBackKeyPressed = false;
                }
            }, 2000);
        } else {//退出程序
            this.finish();
        }
    }

    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }

    public static void checkUpdate(String apkUrl) {
        UpdateAppUtils.getInstance()
                .apkUrl(apkUrl)
                .updateTitle("版本更新")
                .updateContent("更新")
                .update();
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            getDaYin();
            try {
                ChkAndConnectBl();
//                    int i = MainActivity.mZPL.PortOpen("WiFi,192.168.43.114,9100");
                if (TextUtils.isEmpty(userInfoBean.getPrint_ip())) {
                    return;
                }
                try {
                    mZPL.WriteData("~HQES\r\n".getBytes());
                    String str = byteToString(mZPL.ReadData(2)).replace("PRINTER STATUS ERROR:", "");
                    if (str.length() > 0 && str.substring(0, 1).equals("0")) {
                        return;
                    }
                    int i = mZPL.PortOpen("WiFi," + userInfoBean.getPrint_ip() + ",9100");
                    if (i == 0) {
                        System.out.println("连接成功");
                    } else {
                        System.out.println("连接失败");
                    }

                } catch (Exception e) {

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    Runnable runnable1 = new Runnable() {
        @Override
        public void run() {
            try {
                ChkAndConnectBl();
//                    int i = MainActivity.mZPL.PortOpen("WiFi,192.168.43.114,9100");
                if (TextUtils.isEmpty(userInfoBean.getPrint_ip())) {
                    return;
                }
                try {
                    mZPL.WriteData("~HQES\r\n".getBytes());
                    String str = byteToString(mZPL.ReadData(2)).replace("PRINTER STATUS ERROR:", "");
                    if (str.length() > 0 && str.substring(0, 1).equals("0")) {
                        return;
                    }
                    int i = mZPL.PortOpen("WiFi," + userInfoBean.getPrint_ip() + ",9100");
                    if (i == 0) {
                        System.out.println("连接成功");
                    } else {
                        System.out.println("连接失败");
                    }

                } catch (Exception e) {

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private void getDaYin() {
        handler.postDelayed(runnable, 10000);
    }

    public void getDayinStatus() {
        try {
            mZPL.WriteData("~HQES\r\n".getBytes());
            String str = byteToString(mZPL.ReadData(2)).replace("PRINTER STATUS ERROR:", "");
            //str.length() > 0 && str.substring(0, 1).equals("0")
            if (str.length() > 0 && str.substring(0, 1).equals("0")) {
                dyjStatus = true;
                status.setText("连接成功");
                dy_status.setImageResource(R.mipmap.select_true);
                if ((MyApplication.isDyPlay == 0 || MyApplication.isDyPlay == 2) && !MyApplication.dy_scaleIsConnect) {
                    MyApplication.isDyPlay = 1;
                    MyApplication.dy_scaleIsConnect = true;
//                    ToastUtil.getInstance()._short(mContext, "打印机连接成功");
                    playRing("lianjiesuccess.mp3");
                }
                System.out.println("连接成功1");
            } else {
                dyjStatus = false;
                status.setText("连接失败");
                dy_status.setImageResource(R.mipmap.error);
                if ((MyApplication.isDyPlay == 1) && MyApplication.dy_scaleIsConnect) {
                    MyApplication.isDyPlay = 2;
                    MyApplication.dy_scaleIsConnect = false;
//                    ToastUtil.getInstance()._short(mContext, "打印机连接失败");
                    playRing("lianjieerror.mp3");
                }
                System.out.println("连接失败1333");
            }
        } catch (Exception e) {
            status.setText("连接失败");
            dy_status.setImageResource(R.mipmap.error);
            System.out.println("连接失败12");
            if ((MyApplication.isDyPlay == 1) && MyApplication.dy_scaleIsConnect) {
                MyApplication.isDyPlay = 2;
                MyApplication.dy_scaleIsConnect = false;
                playRing("lianjieerror.mp3");
            }
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.e("onResume");
        mPresenter.Into45();
        ReadConfig();
        if (MyApplication.getPort().equals("1"))
            handler.sendEmptyMessage(4);
        getDaYin();
        handler.sendEmptyMessage(2);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            MainActivity.mZPL.PortClose();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        LogUtils.e("onPause");
        handler.removeCallbacks(runnable);
        handler.removeCallbacksAndMessages(null);
    }


    private static String byteToString(byte[] bytes) {
        if (null == bytes || bytes.length == 0) {
            return "";
        }
        String strContent = "";
        try {
            strContent = new String(bytes, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return strContent;
    }

}
